package tn.orange.canreminder.parse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;

public class GenericJsonParser {

	private List<NameValuePair> nameValuePairs;
	@SuppressWarnings("rawtypes")
	private Class Output;
	private String url;

	public GenericJsonParser() {
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Object parse() throws Exception {

		InputStream source = retrieveStream();
		StringBuilder builder = inputStreamToString(source);
		String coder = URLDecoder.decode(builder.toString());
		Gson gson = new Gson();

		return gson.fromJson(coder, Output);

	}

	private InputStream retrieveStream() throws Exception {

		InputStream inputStream = null;
		HttpClient httpclient = new DefaultHttpClient();
		try {
			if (!nameValuePairs.isEmpty()) {
				HttpPost httppost = new HttpPost(url);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse httpResponse = httpclient.execute(httppost);
				return httpResponse.getEntity().getContent();
			} else {
				HttpResponse response = httpclient.execute(new HttpGet(url));
				return response.getEntity().getContent();

			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println();
		}

		return inputStream;

	}

	@SuppressWarnings("rawtypes")
	public Class getOutput() {
		return Output;
	}

	@SuppressWarnings("rawtypes")
	public void setOutput(Class output) {
		Output = output;
	}

	private StringBuilder inputStreamToString(InputStream is)
			throws IOException {
		String line = "";
		StringBuilder total = new StringBuilder();

		// Wrap a BufferedReader around the InputStream
		BufferedReader rd = new BufferedReader(new InputStreamReader(is));

		// Read response until the end
		while ((line = rd.readLine()) != null) {
			total.append(line);
		}

		// Return full string
		return total;
	}

	public List<NameValuePair> getNameValuePairs() {
		return nameValuePairs;
	}

	public void setNameValuePairs(List<NameValuePair> nameValuePairs) {
		this.nameValuePairs = nameValuePairs;
	}

}
